package com.program.config;

import com.program.bean.Permissions;
import com.program.bean.RoleBean;
import com.program.bean.UserBean;
import com.program.service.LoginService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

public class CustomRealm extends AuthorizingRealm {

    @Autowired
    private LoginService loginService;

    /**
     * 权限配置类
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        //获取登录用户信息
		UserBean userBean = (UserBean) principals.getPrimaryPrincipal();

        //查询最新用户信息
        UserBean user = loginService.getLoginUserByName(userBean.getUserName());
        //添加角色和权限
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        for (RoleBean role : user.getRoleBeans()) {
            // 添加角色
            simpleAuthorizationInfo.addRole(role.getRoleName());
            // 添加权限
            for (Permissions permissions : role.getPermissions()) {
                simpleAuthorizationInfo.addStringPermission(permissions.getPermissionsName());
            }
        }
        return simpleAuthorizationInfo;
    }

    /**
     * 认证配置类
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {

        // UsernamePasswordToken对象用来存放提交的登录信息
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        // 实际项目中，这里可以根据实际情况做缓存，如果不做，Shiro自己也是有时间间隔机制，2分钟内不会重复执行该方法
        UserBean user = loginService.getLoginUserByName(token.getUsername());

        if (user == null) {
            throw new UnknownAccountException();
        }
        // 是否激活
        if (user.getStatus() == -1) {
            throw new DisabledAccountException();
        }
        // 是否锁定
        if (user.getStatus() == -2) {
            throw new LockedAccountException();
        }
        //自定义盐
        ByteSource salt = ByteSource.Util.bytes("slat");
        return new SimpleAuthenticationInfo(user, user.getPassword(), salt, getName());

    }
}

